import { DownOutlined, PaperClipOutlined, UpOutlined } from '@ant-design/icons';
import { Timeline, Tooltip } from 'antd';
import { CSSProperties, useState } from 'react';

import { Layout, useAllReady, useAsyncEffect } from '../../util';
import {
  addSubTaskIcon,
  arrowDownIcon,
  arrowDownIcon1,
  arrowDownIcon2,
  arrowUpIcon,
  manIcon,
  reassignIcon,
  rollbackIcon,
  submitIcon,
  subProcessIcon,
  taskRetrieveIcon,
  terminateIcon
} from './constVar';
import { getWorkFlowHis } from './service';
import { setWorkFlowUIState, showTaskAttachment } from './util';

// import './index.less'
const webkitLineClampStyle: CSSProperties = {
  display: '-webkit-box',
  WebkitBoxOrient: 'vertical',
  overflow: 'hidden',
  textOverflow: 'ellipsis',
  WebkitLineClamp: 2,
  lineHeight: '1.5em'
};

const IcontMapp = {
  '1': submitIcon,
  '2': submitIcon, // 会签的同意/提交
  '3': rollbackIcon, // 会签的驳回/回退
  '4': rollbackIcon,
  '5': addSubTaskIcon,
  '6': reassignIcon,
  '90': taskRetrieveIcon,
  '99': terminateIcon
};
const approvalPointRener = (riskLevel) => {
  let approvalPointItem = { color: '#00CC33', name: '无风险' };
  switch (riskLevel) {
    case 1:
      approvalPointItem = { color: '#00CC33', name: '无风险' };
      break;
    case 2:
      approvalPointItem = { color: '#0081CC', name: '低' };
      break;
    case 3:
      approvalPointItem = { color: '#FE890C', name: '中' };
      break;
    case 4:
      approvalPointItem = { color: 'red', name: '高' };
      break;
  }
  return approvalPointItem;
};
const InitWrapStyle = {
  width: '460px',
  backgroundColor: '#FFFFFF'
};
// 附言内容dom
const postScriptListDom = (list) => {
  return (
    <>
      {list &&
        list.length &&
        list.map((v, idx) => {
          return (
            <div
              key={v.id}
              style={{
                padding: '6px 0',
                borderBottom: idx === list.length - 1 ? 'none' : '1px solid rgba(0, 0, 0, .06)'
              }}
            >
              <div style={{ ...webkitLineClampStyle, width: '100%', maxHeight: '46px' }}>
                <Tooltip title={v.postScript}>
                  <span>{v.postScript}</span>
                </Tooltip>
              </div>
              <div
                style={{
                  display: 'flex',
                  justifyContent: 'space-between',
                  fontSize: 12,
                  padding: '3px 0'
                }}
              >
                <span>{v.insertDt}</span>
                {!!v.fileCount && (
                  <span onClick={() => showTaskAttachment(v, 0)} style={{ color: '#0D81CC' }}>
                    <PaperClipOutlined />
                    (x{v.fileCount})
                  </span>
                )}
              </div>
            </div>
          );
        })}
    </>
  );
};
// 附言展开收起
const postScirptListCollapse = (postScriptList: [], index, opened, toggleShowMorePostScript) => {
  let text = opened ? '收起' : '展开更多';
  let icon = opened ? <UpOutlined /> : <DownOutlined />;
  const list: any = opened ? postScriptList : postScriptList.slice(0, 1);
  const renderText = () => {
    return (
      <>
        {postScriptListDom(list)}
        <div
          style={{ height: '26px', fontSize: 12, color: '#0D81CC' }}
          onClick={() => toggleShowMorePostScript(index, opened)}
        >
          <span>
            {text} {icon}
          </span>
        </div>
      </>
    );
  };
  return <div>{renderText()}</div>;
};

const TextExpandCollapse = (text, expanded, index, toggleExpand) => {
  const maxChars = 75; // 最大字符数
  const renderText = () => {
    if (expanded) {
      return (
        <>
          {text}
          <span
            onClick={() => {
              toggleExpand(index, expanded);
            }}
            style={{ cursor: 'pointer', color: 'blue' }}
          >
            收起
          </span>
        </>
      );
    }

    const shouldExpand = text.length > maxChars;
    return (
      <>
        {shouldExpand ? `${text.slice(0, maxChars - 4)}...` : text}
        {shouldExpand && (
          <span
            onClick={() => {
              toggleExpand(index, expanded);
            }}
            style={{ cursor: 'pointer', color: '#0D81CC' }}
          >
            查看全部
          </span>
        )}
      </>
    );
  };

  return <div>{renderText()}</div>;
};
let hisData: any = []; //主流程数据
let subHisData: any = []; //子流程数据
const WfHistoryTimeline = ({ workFlowInfo }) => {
  const [historyList, setHistoryList] = useState(new Array());
  let toggleStateList: any = [];
  const handleToggleContent = async (index, state) => {
    toggleStateList[index] = !state;
    const hisDom = dataToDom(hisData);
    setHistoryList(hisDom);
  };
  let expendedStateList: any = [];
  const toggleExpand = (index, state) => {
    expendedStateList[index] = !state;
    const hisDom = dataToDom(hisData);
    setHistoryList(hisDom);
  };
  let toggleApprovalPointsStateList: any = [];
  //节点内审批要点toggle切换
  const handleToggleApprovalPoints = async (index, state) => {
    toggleApprovalPointsStateList[index] = !state;
    const hisDom = dataToDom(subHisData.length > 0 ? subHisData : hisData);
    setHistoryList(hisDom);
  };
  let postScriptStateList: any = [];
  const toggleShowMorePostScript = (index, state) => {
    postScriptStateList[index] = !state;
    const hisDom = dataToDom(hisData);
    setHistoryList(hisDom);
  };
  //因为Timeline组件需要每次获取新的配置才会生效,所以存一份从接口来的数据 用于每次更新
  const dataToDom = (data) => {
    return data.map((i, index) => {
      return {
        label: (
          <div
            style={{
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              textAlign: 'center',
              marginRight: '-120px'
            }}
          >
            <div style={{ color: '#333333 ' }}>{i.actionName}</div>
            <div style={{ fontSize: '12px', width: '62px', color: '#666666 ' }}>{i.time}</div>
          </div>
        ),
        children: !i.hasOwnProperty('children') ? (
          <div style={{ height: !toggleStateList[index] ? 'auto' : '60px' }}>
            <div
              onClick={() => {
                handleToggleContent(index, toggleStateList[index]);
              }}
              style={{
                width: '287px',
                height: '30px',
                backgroundColor: '#F2F3F4',
                display: 'flex',
                alignItems: 'center',
                paddingLeft: '27px',
                cursor: 'pointer'
              }}
            >
              <span style={{ width: '10px' }}>{!toggleStateList[index] ? arrowUpIcon : arrowDownIcon}</span>
              <span style={{ width: '20px', margin: '0 7px', paddingTop: '6px' }}>{manIcon}</span>
              <span style={{ fontWeight: 'bold' }}>{i.nodeName}</span>
            </div>
            {!toggleStateList[index] && (
              <>
                <div style={{ margin: '11px 0 6px  33px' }}>{i.userName}</div>
                <div style={{ fontSize: '12px', width: '287px', color: '#666666 ', paddingLeft: '33px' }}>
                  {TextExpandCollapse(i.message, expendedStateList[index], index, toggleExpand)}
                </div>
                {!!i.postScriptList && (
                  <div
                    style={{
                      backgroundColor: '#F2F3F4',
                      borderRadius: '4px',
                      width: '260px',
                      margin: '11px 0px 6px 25px',
                      cursor: 'pointer',
                      padding: '0 6px',
                      height: postScriptStateList[index] ? 'auto' : '104px'
                    }}
                  >
                    {postScirptListCollapse(
                      i.postScriptList,
                      index,
                      postScriptStateList[index],
                      toggleShowMorePostScript
                    )}
                  </div>
                )}
                {!!i.fileCount && (
                  <div style={{ fontSize: '12px', width: '62px', color: '#666666 ', marginLeft: '33px' }}>
                    附件:
                    <span style={{ color: '#0D81CC' }}>
                      <PaperClipOutlined
                        onClick={() => {
                          showTaskAttachment(i, 0);
                        }}
                      />
                      {i.fileCount}
                    </span>
                  </div>
                )}
                {!!i.approvalPoints && (
                  <div
                    style={{ fontSize: '12px', width: '287px', marginLeft: '33px', color: '#666666', marginTop: '5px' }}
                  >
                    <span
                      onClick={() => {
                        handleToggleApprovalPoints(index, toggleApprovalPointsStateList[index]);
                      }}
                      style={{
                        display: 'flex',
                        alignItems: 'center',
                        color: '#000000',
                        fontSize: '14px',
                        fontWeight: 'bold',
                        cursor: 'pointer',
                        position: 'relative',
                        left: '-34px'
                      }}
                    >
                      {toggleApprovalPointsStateList[index] ? arrowDownIcon1 : arrowDownIcon2}
                      <span style={{ marginLeft: '5px' }}>审批要点:</span>
                    </span>
                    {toggleApprovalPointsStateList[index] &&
                      i.approvalPointRuntimeDtoList.map((j, index) => {
                        return (
                          <div style={{ marginTop: '10px' }}>
                            <div>
                              <span
                                style={{
                                  display: 'inline-block',
                                  width: '16px',
                                  height: '16px',
                                  borderRadius: '50%',
                                  backgroundColor: '#0081cc',
                                  color: '#ffffff',
                                  textAlign: 'center',
                                  fontSize: '12px',
                                  lineHeight: '16px',
                                  marginRight: '2px'
                                }}
                              >
                                {index + 1}
                              </span>
                              <span style={{ fontWeight: 'bold' }}>{j.name}</span>
                            </div>
                            <div style={{ marginLeft: '18px' }}>{j.description}</div>
                            <div
                              style={{
                                color: approvalPointRener(j.details?.[0].riskLevel).color,
                                marginLeft: '18px',
                                marginBottom: '5px',
                                fontWeight: 'bold'
                              }}
                            >
                              {approvalPointRener(j.details?.[0].riskLevel).name}
                            </div>
                            <div
                              style={{
                                width: 'max-content',
                                border: '1px solid #0281CC',
                                borderRadius: '3px',
                                marginLeft: '18px',
                                padding: '3px 6px 3px 6px',
                                color: '#0281CC',
                                backgroundColor: '#E5F8FF '
                              }}
                            >
                              {j.details?.[0].optionValue}
                            </div>
                            {j.details?.[0].remark && <div>备注：{j.details?.[0].remark}</div>}
                          </div>
                        );
                      })}
                  </div>
                )}
              </>
            )}
          </div>
        ) : (
          <div
            style={{
              height: '50px'
            }}
          >
            <div
              onClick={() => {
                const hisDom = dataToDom(i.children);
                subHisData = i.children;
                setHistoryList(hisDom);
              }}
              style={{
                width: '287px',
                height: '30px',
                backgroundColor: '#F2F3F4',
                display: 'flex',
                alignItems: 'center',
                paddingLeft: '22px',
                cursor: 'pointer'
              }}
            >
              <span style={{ width: '20px', margin: '0 7px', paddingTop: '6px' }}>{subProcessIcon}</span>
              <span style={{ fontWeight: 'bold' }}>子流程</span>
            </div>
          </div>
        ),
        dot: <span>{IcontMapp[i.action ? i.action : '1']}</span>
      };
    });
  };

  useAsyncEffect(async () => {
    hisData = await getWorkFlowHis({ procInstId: workFlowInfo.procInstId || '' });
    const hisDom = dataToDom(hisData);
    setHistoryList(hisDom);
  }, [workFlowInfo.procInstId]);

  return (
    <Timeline style={{ position: 'relative', left: '-100px', paddingTop: '40px' }} mode={'left'} items={historyList} />
  );
};

/**
 * 审批流历史组件
 * @param options 相关配置
 * @constructor
 */
export function WFVerticalHisLayout({ workFlowInfo, styles = undefined }) {
  const wrapStyle = styles ? styles : InitWrapStyle;
  useAllReady(() => {
    setWorkFlowUIState(workFlowInfo.formDataPermissions, workFlowInfo.menuPermissions);
  });
  return (
    <Layout style={wrapStyle}>
      <WfHistoryTimeline workFlowInfo={workFlowInfo} />
    </Layout>
  );
}
